import COS from 'cos-nodejs-sdk-v5';
import * as fs from 'fs-extra';
import { CloudServiceInterface, FileInfo, CloudConfig } from '../types';
import { Logger } from '../../utils/Logger';

export class TencentCloudService implements CloudServiceInterface {
  private cos: COS;
  private config: CloudConfig;

  constructor(config: CloudConfig) {
    this.config = config;
    this.cos = new COS({
      SecretId: config.accessKeyId,
      SecretKey: config.secretAccessKey
    });
  }

  /**
   * 上传文件
   */
  async uploadFile(
    filePath: string,
    remotePath: string,
    onProgress?: (progress: number) => void
  ): Promise<boolean> {
    return new Promise((resolve, reject) => {
      const fileStream = fs.createReadStream(filePath);
      const stat = fs.statSync(filePath);
      
      this.cos.putObject({
        Bucket: this.config.bucket,
        Region: this.config.region,
        Key: remotePath,
        Body: fileStream,
        ContentLength: stat.size,
        onProgress: (progressData) => {
          if (onProgress) {
            const progress = (progressData.loaded / progressData.total) * 100;
            onProgress(progress);
          }
        }
      }, (err, data) => {
        if (err) {
          Logger.error('腾讯云上传失败:', err);
          reject(err);
        } else {
          Logger.info('腾讯云上传成功:', data);
          resolve(true);
        }
      });
    });
  }

  /**
   * 列出文件
   */
  async listFiles(remotePath: string): Promise<FileInfo[]> {
    return new Promise((resolve, reject) => {
      const files: FileInfo[] = [];
      
      // 处理路径格式：移除前导斜杠
      const prefix = remotePath.startsWith('/') ? remotePath.substring(1) : remotePath;
      Logger.info(`腾讯云 listFiles - 原始路径: ${remotePath}, 处理后路径: ${prefix}`);
      
      const listObjects = (marker?: string) => {
        const params = {
          Bucket: this.config.bucket,
          Region: this.config.region,
          Prefix: prefix,
          Marker: marker,
          MaxKeys: 1000
        };
        
        Logger.info('腾讯云 getBucket 请求参数:', JSON.stringify(params, null, 2));
        
        this.cos.getBucket(params, (err, data) => {
          if (err) {
            Logger.error('腾讯云列出文件失败:', err);
            Logger.error('错误详情:', JSON.stringify(err, null, 2));
            reject(err);
            return;
          }

          Logger.info('腾讯云 getBucket 响应数据:', JSON.stringify(data, null, 2));
          
          if (data.Contents) {
            Logger.info(`腾讯云找到 ${data.Contents.length} 个文件`);
            data.Contents.forEach(item => {
              files.push({
                key: item.Key,
                size: parseInt(item.Size),
                lastModified: new Date(item.LastModified),
                etag: item.ETag.replace(/"/g, '')
              });
            });
          } else {
            Logger.info('腾讯云响应中没有 Contents 字段');
          }

          // 如果还有更多文件，继续获取
          if (data.IsTruncated === 'true' && data.NextMarker) {
            Logger.info('还有更多文件，继续获取...');
            listObjects(data.NextMarker);
          } else {
            Logger.info(`腾讯云 listFiles 完成，共获取 ${files.length} 个文件`);
            resolve(files);
          }
        });
      };
      
      listObjects();
    });
  }

  /**
   * 删除文件
   */
  async deleteFile(remotePath: string): Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.cos.deleteObject({
        Bucket: this.config.bucket,
        Region: this.config.region,
        Key: remotePath
      }, (err, data) => {
        if (err) {
          Logger.error('腾讯云删除文件失败:', err);
          reject(err);
        } else {
          Logger.info('腾讯云删除文件成功:', data);
          resolve(true);
        }
      });
    });
  }

  /**
   * 测试连接
   */
  async testConnection(): Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.cos.headBucket({
        Bucket: this.config.bucket,
        Region: this.config.region
      }, (err, data) => {
        if (err) {
          Logger.error('腾讯云连接测试失败:', err);
          resolve(false);
        } else {
          Logger.info('腾讯云连接测试成功:', data);
          resolve(true);
        }
      });
    });
  }

  /**
   * 获取文件URL
   */
  getFileUrl(remotePath: string): string {
    return this.cos.getObjectUrl({
      Bucket: this.config.bucket,
      Region: this.config.region,
      Key: remotePath,
      Sign: false
    });
  }
}